package com.mediacloud.app.newsmodule.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.album.live.AreaLiveListAdapter
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.utils.RxUtils
import com.mediacloud.app.util.ClickUtils
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_area_live_list.*
import org.json.JSONArray
import org.json.JSONObject
import java.util.ArrayList
import java.util.HashMap

/**
 * 地区下的直播 列表
 */
class AreaLiveListActivity : BaseBackActivity(), OnRefreshLoadMoreListener {

    private var areaArticleItem:ArticleItem?=null


    private val mDataList: MutableList<ArticleItem> = ArrayList<ArticleItem>()
    //    private var mAdapter: BangDanHomeListAdapter? = null
    private var mAdapter: AreaLiveListAdapter? = null
    private var mPageIndex: Int = 1
    private var PAGE_SIZE: Int = 20
    private var mTitleStr: String? = null
    private var mRcatalogid:String?=null
    private var catalogItem=CatalogItem()
    companion object {
        @JvmStatic
        fun startActivity(context: Context?,areaArticleItem:ArticleItem?) {
            if (context == null) {
                return
            }
            val intent = Intent(context, AreaLiveListActivity::class.java)
            intent.putExtra("title", areaArticleItem?.title)
            intent.putExtra("data",areaArticleItem)
            context.startActivity(intent)
        }
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_area_live_list
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mTitleStr=intent.getStringExtra("title")
        areaArticleItem=intent.getParcelableExtra("data")
        catalogItem?.catid="${areaArticleItem?.catalogId}"
        catalogItem?.catname="${areaArticleItem?.catalogName}"
        try {
            val param: JSONObject? = JSONObject(areaArticleItem?.appCustomParams)
            mRcatalogid=param?.optJSONObject("movie")?.optString("Rcatalogid")
        }catch (e:Exception){
            e.printStackTrace()
        }


        setTitle(mTitleStr)
        initView()
        initRecyclerView()
        initListener()

        onRefresh()
    }
    fun initView() {
        loadingView = mLoadingView
        initStateView()
    }
    private fun initRecyclerView() {
        mAdapter = AreaLiveListAdapter(mDataList)
        recyclerView.layoutManager = ViewUtils.generateRecyclerLinearLayoutManager(this,true)
        mAdapter?.bindToRecyclerView(recyclerView)
    }
    private fun initListener() {
        refreshLayout.setOnRefreshLoadMoreListener(this)
        loadingView.setOnClickListener {
            if (TYPE_LOADING != currentState) {
                showStateView(TYPE_LOADING, false)
                onRefresh()
            }
        }
        mAdapter?.setOnItemClickListener { adapter, view, position ->
            ClickUtils.delayClickable(view)
            mAdapter?.data?.get(position)?.let {

                NewsItemClickUtils.OpenItemNewsHandle(this, it.getType(), it, catalogItem)
            }
        }

    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        onRefresh()

    }

    private fun onRefresh() {
        mPageIndex = 1
        getList()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        onLoadMore()
    }

    private fun onLoadMore() {
        mPageIndex++
        getList()
    }





    val compositeDisposable = CompositeDisposable()
    fun getList() {
        val map: MutableMap<String, Any> = HashMap()
        map["catalog_id"] = "${mRcatalogid?:""}"
        map["page"] = mPageIndex
        map["perPage"] = PAGE_SIZE

        DataInvokeUtil.getZiMeiTiApi().getArticleCmsList(map)
                .compose(RxUtils.schedulersTransformer())
                .subscribe({
                    if (isFinishing) {
                        return@subscribe
                    }

                    var isHasNextPage: Boolean = false
                    if (mPageIndex == 1) {
                        refreshLayout.finishRefresh()
                        mDataList.clear()
                        mAdapter?.replaceData(mDataList)
                    } else {
                        refreshLayout.finishLoadMore()
                    }
                    val tempList:MutableList<ArticleItem> = ArrayList()
                    if (it.optBoolean("state")) {

                        var data: JSONObject?  = it.optJSONObject("data")
                        val meta:JSONArray? = data?.optJSONArray("meta")

                        val paging:JSONObject? = data?.optJSONObject("paging")
                        paging?.let {
                            isHasNextPage = it.optInt("lastPage", 1) != it.optInt("currentPage", 1)
                        }
                        try {
                            meta?.let {
                                for (i in 0 until it.length()) {
                                    val item = ArticleItem.parse(meta.optJSONObject(i))
                                    tempList.add(item)
                                }
                            }
                        }catch (e:Exception){
                            e.printStackTrace()
                        }
                    }
                    mAdapter?.addData(tempList)
                    if (mPageIndex == 1) {
                        if (mAdapter?.data == null || mAdapter?.data?.size == 0) {
                            showStateView(TYPE_NO_CONTENT, false)
                        } else {
                            closeStateView()
                        }
                    }
                    if (isHasNextPage) {
                            refreshLayout.setEnableLoadMore(true)
                            refreshLayout.setNoMoreData(false)
                    } else {
                        refreshLayout.setNoMoreData(false)
                    }
                },{
                    if (isFinishing) {
                        return@subscribe
                    }
                    if (mPageIndex == 1) {
                        refreshLayout.finishRefresh()
                        if (it != null && (mAdapter?.data == null || mAdapter?.data?.size == 0)) {
                            showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                            it.printStackTrace()
                        } else if (mAdapter?.data == null || mAdapter?.data?.size == 0) {
                            showStateView(TYPE_NO_CONTENT, false)
                        } else {
                            closeStateView()
                        }
                    } else {
                        refreshLayout.finishLoadMore()
                        if (mPageIndex > 1) {
                            mPageIndex--
                        }
                    }
                },{

                },{
                    compositeDisposable.add(it)
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        compositeDisposable.dispose()
    }
}